<?php

namespace frontend\controllers;

use phpDocumentor\Reflection\Types\Object_;
use Yii;
use common\models\LifeTime;

class BabyLifeController extends \yii\web\Controller
{
    public $layout = false;

    public function actionTake()
    {
        $request = Yii::$app->getRequest();

        if($request->isPost){
            $sign = $request->post('sign','');
            $action = (int)$request->post('action',0);
            $action_time = $request->post('time',0);
            $self_sign = Yii::$app->params['sign'];

            if(
                $sign != $self_sign ||
                !isset( LifeTime::$action[$action] )
            ){
                return ['code'=>1];
            }

            if($action_time == 0 || strlen($action_time) != 10){
                $action_time = time();
            }

            $lifeTime = new LifeTime();
            $lifeTime->life_action = $action;
            $lifeTime->action_time = $action_time;
            $lifeTime->save();
            return ['code'=>0,'time'=>$action_time];
        }

      return (new \stdClass());
    }

    public function actionLastTimes(){
        $request = Yii::$app->getRequest();
        $sign = $request->get('sign','');
        $self_sign = Yii::$app->params['sign'];

        if( $sign != $self_sign){
            return ['code'=>1];
        }

        $data = LifeTime::find()->select('life_action,MAX(`action_time`) as action_time')
                                ->groupBy('life_action')->all();

        $return_data = array_column($data,'action_time','life_action');
        if(count($return_data) == 0 ) $return_data = new \stdClass();

        $res = [
            'code'=>0,
            'data'=>$return_data,
        ];

        return $res;
    }


}
